<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/favicon.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.ico">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.7.2/css/all.min.css" integrity="sha256-dABdfBfUoC8vJUBOwGVdm8L9qlMWaHTIfXt+7GnZCIo=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"blog.csgrandeur.cn","root":"/","images":"/images","scheme":"Gemini","darkmode":false,"version":"8.22.0","exturl":false,"sidebar":{"position":"left","width_expanded":320,"width_dual_column":240,"display":"post","padding":18,"offset":12},"hljswrap":true,"copycode":{"enable":true,"style":"default"},"fold":{"enable":false,"height":500},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"duration":200,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"top_n_per_article":1,"unescape":false,"preload":false,"trigger":"auto"}}</script><script src="/js/config.js"></script>

    <meta name="description" content="双指针（尺取） 通过两个（或多个）移动的标记，高效地探索或处理数据结构中的连续部分，以简化问题并加快求解速度，通常称为双指针、尺取或滑动窗口等。">
<meta property="og:type" content="article">
<meta property="og:title" content="21.双指针（尺取）">
<meta property="og:url" content="http://blog.csgrandeur.cn/2025-04-05-21-%E5%8F%8C%E6%8C%87%E9%92%88%EF%BC%88%E5%B0%BA%E5%8F%96%EF%BC%89/index.html">
<meta property="og:site_name" content="CSGrandeur&#39;s Thinking">
<meta property="og:description" content="双指针（尺取） 通过两个（或多个）移动的标记，高效地探索或处理数据结构中的连续部分，以简化问题并加快求解速度，通常称为双指针、尺取或滑动窗口等。">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2025-04-05T03:21:36.000Z">
<meta property="article:modified_time" content="2025-04-10T04:41:18.552Z">
<meta property="article:author" content="CSGrandeur">
<meta property="article:tag" content="ACM">
<meta property="article:tag" content="Algorithm">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="http://blog.csgrandeur.cn/2025-04-05-21-%E5%8F%8C%E6%8C%87%E9%92%88%EF%BC%88%E5%B0%BA%E5%8F%96%EF%BC%89/">


<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://blog.csgrandeur.cn/2025-04-05-21-%E5%8F%8C%E6%8C%87%E9%92%88%EF%BC%88%E5%B0%BA%E5%8F%96%EF%BC%89/","path":"2025-04-05-21-双指针（尺取）/","title":"21.双指针（尺取）"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>21.双指针（尺取） | CSGrandeur's Thinking</title>
  

  <script src="/js/third-party/analytics/baidu-analytics.js"></script>
  <script async src="https://hm.baidu.com/hm.js?7958adf931092425a489778560129144"></script>







  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">CSGrandeur's Thinking</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">Cogito Ergo Sum</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
      <div class="search-header">
        <span class="search-icon">
          <i class="fa fa-search"></i>
        </span>
        <div class="search-input-container">
          <input autocomplete="off" autocapitalize="off" maxlength="80"
                placeholder="搜索..." spellcheck="false"
                type="search" class="search-input">
        </div>
        <span class="popup-btn-close" role="button">
          <i class="fa fa-times-circle"></i>
        </span>
      </div>
      <div class="search-result-container">
        <div class="search-result-icon">
          <i class="fa fa-spinner fa-pulse fa-5x"></i>
        </div>
      </div>
    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%8F%8C%E6%8C%87%E9%92%88%E5%B0%BA%E5%8F%96"><span class="nav-number">1.</span> <span class="nav-text">双指针（尺取）</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BE%8B%E5%8D%95%E8%AF%8D%E8%83%8C%E8%AF%B5"><span class="nav-number">1.1.</span> <span class="nav-text">例：单词背诵</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BE%8B%E6%8C%91%E9%80%89%E9%92%BB%E7%9F%B3"><span class="nav-number">1.2.</span> <span class="nav-text">例：挑选钻石</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">CSGrandeur</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">72</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">22</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://blog.csgrandeur.cn/2025-04-05-21-%E5%8F%8C%E6%8C%87%E9%92%88%EF%BC%88%E5%B0%BA%E5%8F%96%EF%BC%89/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="CSGrandeur">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="CSGrandeur's Thinking">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="21.双指针（尺取） | CSGrandeur's Thinking">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          21.双指针（尺取）
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2025-04-05 11:21:36" itemprop="dateCreated datePublished" datetime="2025-04-05T11:21:36+08:00">2025-04-05</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">更新于</span>
      <time title="修改时间：2025-04-10 12:41:18" itemprop="dateModified" datetime="2025-04-10T12:41:18+08:00">2025-04-10</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/ACM/" itemprop="url" rel="index"><span itemprop="name">ACM</span></a>
        </span>
          ，
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/ACM/ACMCOURSE/" itemprop="url" rel="index"><span itemprop="name">ACMCOURSE</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><h1 id="双指针尺取">双指针（尺取）</h1>
<p>通过两个（或多个）移动的标记，高效地探索或处理数据结构中的连续部分，以简化问题并加快求解速度，通常称为双指针、尺取或滑动窗口等。</p>
<span id="more"></span>
<h2 id="例单词背诵">例：单词背诵</h2>
<p>给一个单词表以及一个文章，要在文章里找包含单词表中单词最多的前提下最短的一段。</p>
<p>进一步解释：在文章中找到起点第 <span class="math inline">\(i\)</span>
个单词，终点第 <span class="math inline">\(j\)</span>
个单词，包含单词表中单词数量最多的<span
class="math inline">\([i,j]\)</span>
区间可能不唯一，找最短的那个区间。</p>
<p>输入 <span class="math inline">\(n\)</span> 然后 <span
class="math inline">\(n\)</span> 个单词的单词表，接着输入 <span
class="math inline">\(m\)</span> 然后 <span
class="math inline">\(m\)</span> 个单词的文章。</p>
<p>输入</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">3</span><br><span class="line">hot</span><br><span class="line">dog</span><br><span class="line">milk</span><br><span class="line">5</span><br><span class="line">hot</span><br><span class="line">dog</span><br><span class="line">dog</span><br><span class="line">milk</span><br><span class="line">hot</span><br></pre></td></tr></table></figure>
<p>输出</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">3</span><br><span class="line">3</span><br></pre></td></tr></table></figure>
<p>这道题有“包含最多”和“长度最短”两个要求，而“包含最多”的要求是优先的，这说明要不放弃任何一个包含的单词。</p>
<p>将起点 <span class="math inline">\(j\)</span> 和终点 <span
class="math inline">\(i\)</span> 设置为双指针， <span
class="math inline">\(i\)</span> 先走。</p>
<ol type="1">
<li><span class="math inline">\(i\)</span> 走一步：
<ul>
<li>文章第 <span class="math inline">\(i\)</span>
个单词是否是单词表里的单词</li>
<li>目前的 <span class="math inline">\([j,i]\)</span>
区间包含了这个单词几次</li>
</ul></li>
<li><span class="math inline">\(j\)</span> （可能）走多步：
<ul>
<li>文章第 <span class="math inline">\(j\)</span>
个单词如果不是单词表里的， <span class="math inline">\(j\)</span>
向前走一步</li>
<li>文章第 <span class="math inline">\(j\)</span>
个单词是单词表里的，且目前 <span class="math inline">\([j,i]\)</span>
区间包含不止一个， <span class="math inline">\(j\)</span>
向前走一步</li>
<li>文章第 <span class="math inline">\(j\)</span>
个单词是单词表里的，但目前 <span class="math inline">\([j,i]\)</span>
区间里只有 1 个，<span class="math inline">\(j\)</span>
停下，不再尝试往前走</li>
</ul></li>
<li>现在 <span class="math inline">\([j,i]\)</span>
包含单词数是否增多，<span
class="math inline">\([j,i]\)</span>长度（<code>i-j+1</code>）是否更短，更新答案</li>
<li>重复执行 1) ~ 3)</li>
</ol>
<p>关于是否包含、包含几个的问题，我们学过hash和字典树都可以很容易处理了，当然如果你已熟练掌握，那么现在可以用STL的<code>map</code>或<code>unorderd_map</code>。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;cstdio&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;algorithm&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;map&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;string&gt;</span></span></span><br><span class="line"><span class="type">const</span> <span class="type">int</span> maxn = <span class="number">1e3</span> + <span class="number">10</span>;</span><br><span class="line"><span class="type">const</span> <span class="type">int</span> maxm = <span class="number">1e5</span> + <span class="number">10</span>;</span><br><span class="line"></span><br><span class="line"><span class="type">char</span> a[maxn][<span class="number">21</span>], b[maxm][<span class="number">21</span>];</span><br><span class="line"><span class="type">int</span> n, m;</span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="built_in">scanf</span>(<span class="string">&quot;%d&quot;</span>, &amp;n);</span><br><span class="line">    std::map&lt;std::string, <span class="type">int</span>&gt; mp;</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> i = <span class="number">0</span>; i &lt; n; i ++) &#123;</span><br><span class="line">        <span class="built_in">scanf</span>(<span class="string">&quot;%s&quot;</span>, a[i]);</span><br><span class="line">        mp[a[i]] = <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">scanf</span>(<span class="string">&quot;%d&quot;</span>, &amp;m);</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> i = <span class="number">0</span>; i &lt; m; i ++) &#123;</span><br><span class="line">        <span class="built_in">scanf</span>(<span class="string">&quot;%s&quot;</span>, b[i]);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="type">int</span> tmp_cnt = <span class="number">0</span>, ans_cnt = <span class="number">0</span>, ans_len = m;</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> i = <span class="number">0</span>, j = <span class="number">0</span>; i &lt; m; i ++) &#123;</span><br><span class="line">        <span class="keyword">if</span>(mp.<span class="built_in">count</span>(b[i])) &#123;    <span class="comment">// map的count查询是否包含</span></span><br><span class="line">            mp[b[i]] ++;        <span class="comment">// 包含则计数+1</span></span><br><span class="line">            <span class="keyword">if</span>(mp[b[i]] == <span class="number">1</span>) &#123; <span class="comment">// 首次计入</span></span><br><span class="line">                tmp_cnt ++;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">while</span>(j &lt;= i) &#123;</span><br><span class="line">            <span class="keyword">if</span>(mp.<span class="built_in">count</span>(b[j])) &#123;    <span class="comment">// b[j] 是否在单词表中</span></span><br><span class="line">                <span class="keyword">if</span>(mp[b[j]] &gt; <span class="number">1</span>) &#123;  <span class="comment">// [j, i] 是否有不止一个</span></span><br><span class="line">                    mp[b[j]] --;    <span class="comment">// j要向前走，统计值减一</span></span><br><span class="line">                &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                    <span class="keyword">break</span>;          <span class="comment">// [j,i] 只包含一个b[j]，不能丢掉它，结束本次循环</span></span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            j ++;                   <span class="comment">// j 向前走</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span>(tmp_cnt &gt;= ans_cnt) &#123;    <span class="comment">// 总结当前 [j,i] 区间对答案的更新</span></span><br><span class="line">            <span class="keyword">if</span>(tmp_cnt &gt; ans_cnt || i - j + <span class="number">1</span> &lt; ans_len) &#123;</span><br><span class="line">                ans_len = i - j + <span class="number">1</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            ans_cnt = tmp_cnt;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;%d\n%d\n&quot;</span>, ans_cnt, ans_len);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="例挑选钻石">例：挑选钻石</h2>
<p>给定 <span class="math inline">\(N\)</span> 颗钻石的大小和一个整数
<span class="math inline">\(K\)</span>（<span class="math inline">\(N
\leq 50,000\)</span>, <span class="math inline">\(0 \leq K \leq
1,000,000,000\)</span>），你的任务是确定可以在两个展示柜中展示的最大钻石数量。如果两颗钻石的大小之差超过
<span
class="math inline">\(K\)</span>，则它们不能放在同一个展示柜中；若大小之差恰好为
<span class="math inline">\(K\)</span>，则可以放在同一个展示柜中。</p>
<p>分析：如果把 <span class="math inline">\(N\)</span>
个数排序，那么答案就是找两个不重叠的子串，每个子串最大值与最小值差不超过<span
class="math inline">\(K\)</span>，两个子串长度之和最大的方案。</p>
<p>在排序后，先考虑找一个这样的子串的最大方案怎么找：双指针保持 <span
class="math inline">\(i\)</span> 和 <span
class="math inline">\(j\)</span> 的价值之差不超过 <span
class="math inline">\(K\)</span>，统计最长的一段。</p>
<p>考虑找两个不重叠的：如果对任意划分界限，界限左边找一段最长的，界限右边也找一段最长的，最优方案一定在某一个界限时得到。</p>
<p>需要快速知道确定界限时，左边和右边各自的最优解。</p>
<ul>
<li>从左往右双指针一遍：记录每个位置作为界限，左边的最优解</li>
<li>从右往左双指针一遍：记录每个位置作为界限，右边的最优解</li>
<li>枚举界限，把左右最优解加起来，找全局最优</li>
</ul>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;cstdio&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;cstring&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;cstdlib&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;algorithm&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;map&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;string&gt;</span></span></span><br><span class="line"><span class="type">const</span> <span class="type">int</span> maxn = <span class="number">5e4</span> + <span class="number">10</span>;</span><br><span class="line"><span class="type">int</span> n, k, a[maxn], l_max[maxn], r_max[maxn];</span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="built_in">scanf</span>(<span class="string">&quot;%d%d&quot;</span>, &amp;n, &amp;k);</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> i = <span class="number">0</span>; i &lt; n; i ++) &#123;</span><br><span class="line">        <span class="built_in">scanf</span>(<span class="string">&quot;%d&quot;</span>, &amp;a[i]);</span><br><span class="line">    &#125;</span><br><span class="line">    std::<span class="built_in">sort</span>(a, a + n);</span><br><span class="line">    <span class="built_in">memset</span>(l_max, <span class="number">0</span>, <span class="built_in">sizeof</span>(l_max));</span><br><span class="line">    <span class="built_in">memset</span>(r_max, <span class="number">0</span>, <span class="built_in">sizeof</span>(r_max));</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> i = <span class="number">0</span>, j = <span class="number">0</span>; i &lt; n; i ++) &#123;        <span class="comment">// 双指针较快的 i</span></span><br><span class="line">        <span class="keyword">for</span>(;j &lt; i &amp;&amp; a[i] - a[j] &gt; k; j ++);   <span class="comment">// 双指针跟随的 j，保持在刚刚好不超过 K 的最远位置</span></span><br><span class="line">        <span class="comment">// 以 i 为界限的左边最优解，应当是 “以 i 为结尾的新方案” 和 “之前的方案” 的最优的那个</span></span><br><span class="line">        l_max[i] = std::<span class="built_in">max</span>(i &gt; <span class="number">0</span> ? l_max[i - <span class="number">1</span>] : <span class="number">0</span>, i - j + <span class="number">1</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 从右往左同理，处理好坐标方向和边界</span></span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> i = n - <span class="number">1</span>, j = n - <span class="number">1</span>; i &gt;= <span class="number">0</span>; i --) &#123;</span><br><span class="line">        <span class="keyword">for</span>(;j &gt; i &amp;&amp; a[j] - a[i] &gt; k; j --);</span><br><span class="line">        r_max[i] = std::<span class="built_in">max</span>(i &lt; n - <span class="number">1</span> ? r_max[i + <span class="number">1</span>] : <span class="number">0</span>, j - i + <span class="number">1</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 在每个位置作为界限尝试</span></span><br><span class="line">    <span class="type">int</span> ans = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> i = <span class="number">0</span>; i &lt; n; i ++) &#123;</span><br><span class="line">        ans = std::<span class="built_in">max</span>(ans, l_max[i] + r_max[i + <span class="number">1</span>]);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;%d\n&quot;</span>, ans);</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>界限往右的预处理也可以省略：如果已经得到了任意界限左边的最优解（不一定是以界限为结尾的解），从界限出发往右找最远位置，与界限左边的最优解合起来也就可以了。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;cstdio&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;cstring&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;cstdlib&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;algorithm&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;map&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;string&gt;</span></span></span><br><span class="line"><span class="type">const</span> <span class="type">int</span> maxn = <span class="number">5e4</span> + <span class="number">10</span>;</span><br><span class="line"><span class="type">int</span> n, k, a[maxn];</span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="built_in">scanf</span>(<span class="string">&quot;%d%d&quot;</span>, &amp;n, &amp;k);</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> i = <span class="number">0</span>; i &lt; n; i ++) &#123;</span><br><span class="line">        <span class="built_in">scanf</span>(<span class="string">&quot;%d&quot;</span>, &amp;a[i]);</span><br><span class="line">    &#125;</span><br><span class="line">    std::<span class="built_in">sort</span>(a, a + n);</span><br><span class="line">    <span class="type">int</span> ans = <span class="number">0</span>, l_max = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> i = <span class="number">0</span>, j = <span class="number">0</span>, r = <span class="number">0</span>; i &lt; n; i ++) &#123;</span><br><span class="line">        <span class="keyword">for</span>(;j &lt; i &amp;&amp; a[i] - a[j] &gt; k; j ++);                       <span class="comment">// [j,i]</span></span><br><span class="line">        l_max = std::<span class="built_in">max</span>(l_max, i - j + <span class="number">1</span>);</span><br><span class="line">        <span class="keyword">for</span>(; r &lt; n &amp;&amp; i &lt; n - <span class="number">1</span> &amp;&amp; a[r] - a[i + <span class="number">1</span>] &lt;= k; r ++);    <span class="comment">// [i+1, r-1]</span></span><br><span class="line">        ans = std::<span class="built_in">max</span>(ans, r - i - <span class="number">1</span> + l_max);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;%d\n&quot;</span>, ans);</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/ACM/" rel="tag"># ACM</a>
              <a href="/tags/Algorithm/" rel="tag"># Algorithm</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2025-04-03-20-%E7%A6%BB%E6%95%A3%E5%8C%96/" rel="prev" title="20.离散化">
                  <i class="fa fa-angle-left"></i> 20.离散化
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2025-04-05-22-%E5%8D%95%E8%B0%83%E6%A0%88/" rel="next" title="22.单调栈">
                  22.单调栈 <i class="fa fa-angle-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






    <div class="comments utterances-container"></div>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="copyright">
    &copy; 
    <span itemprop="copyrightYear">2025</span>
    <span class="with-love">
      <i class="fa fa-heart"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">CSGrandeur</span>
  </div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>
  <div class="sidebar-dimmer"></div>
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="https://fastly.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="https://fastly.jsdelivr.net/npm/@next-theme/pjax@0.6.0/pjax.min.js" integrity="sha256-vxLn1tSKWD4dqbMRyv940UYw4sXgMtYcK6reefzZrao=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/sidebar.js"></script><script src="/js/next-boot.js"></script><script src="/js/pjax.js"></script>

  <script src="https://fastly.jsdelivr.net/npm/hexo-generator-searchdb@1.4.1/dist/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>







  




  

  <script class="next-config" data-name="enableMath" type="application/json">true</script><script class="next-config" data-name="mathjax" type="application/json">{"enable":true,"tags":"none","js":{"url":"https://fastly.jsdelivr.net/npm/mathjax@3.2.2/es5/tex-mml-chtml.js","integrity":"sha256-MASABpB4tYktI2Oitl4t+78w/lyA+D7b/s9GEP0JOGI="}}</script>
<script src="/js/third-party/math/mathjax.js"></script>


<script class="next-config" data-name="utterances" type="application/json">{"enable":true,"repo":"CSGrandeur/csgrandeur.github.io","issue_term":"pathname","theme":"github-light"}</script>
<script src="/js/third-party/comments/utterances.js"></script>

</body>
</html>
